
package poker.plans.player;

import poker.beliefs.*;
import jadex.adapter.fipa.*;
import jadex.runtime.IGoal;
import jadex.runtime.IMessageEvent;
import jadex.runtime.Plan;

/**
 *  Plan to join a poker game by contacting a croupier.
 */

public class JoinGamePlan extends Plan {

	public void body() {
		/*
		 * Find the croupier in the DF
		 */
        System.out.println("PLAYER " + getAgentName() + " - Searching for the croupier...");
        
        // Create a service description to search for
        ServiceDescription sd = new ServiceDescription();
        sd.setType("poker");
        AgentDescription dfAgDesc = new AgentDescription();
        dfAgDesc.addService(sd);
        SearchConstraints sc = new SearchConstraints();
        sc.setMaxResults(1);

        // Use a subgoal to search for a croupier agent
        IGoal ft = createGoal("df_search");
        ft.getParameter("description").setValue(dfAgDesc);
        ft.getParameter("constraints").setValue(sc);
        dispatchSubgoalAndWait(ft);
        AgentDescription[] result = (AgentDescription[])ft.getParameterSet("result").getValues();
    
        if (result == null || result.length == 0) {
        	System.out.println("PLAYER " + getAgentName() + " - No poker croupier found");
        	fail();
        }
        
        // Croupier AgentDescription found, update the belief base
        AgentIdentifier croupier = result[0].getName();
        getBeliefbase().getBelief("croupier").setFact(croupier);
        System.out.println("PLAYER " + getAgentName() + " - Found croupier " + croupier.getName());
        
        /*
		 * Contact the croupier for registering
		 */
        RequestJoin rj = new RequestJoin();
        rj.setPlayer(croupier);
        IMessageEvent msg = createMessageEvent("request_join");
        msg.getParameterSet(SFipa.RECEIVERS).addValue(croupier);
        msg.setContent(rj);
        
        // Send the join message and wait for a response
        System.out.println("PLAYER " + getAgentName() + " - Sending join message to croupier " + croupier.getName());
        sendMessageAndWait(msg, 10000);
	}
	
	
	public void failed() {
            // Remove croupier fact
            getBeliefbase().getBelief("croupier").setFact(null);
    }

}
